const moneyType = {
  minute: 1,
  yuan: 3,
};

/**
 * 元角分转化
 * @date   2019-07-08
 * @param {[money]} number
 * @param {[from]} 
 * @param {[to]}
 * @return {number}   
 */
export function formatMoney({
  money,
  from = 'minute',
  to = 'yuan',
}) {
  if (!moneyType[from] || !moneyType[to]) {
    throw new Error('传入的参数有误');
  }
  const diff = moneyType[from] - moneyType[to];
  return money * Math.pow(10, diff);
}

const types = {
  1: '[object Object]',
  2: '[object Number]',
  3: '[object String]',
};

function TypeJudgment({
  arg,
  type = 1,
}) {
  return Reflect.toString.call(arg) === types[type];
}

export function isObject(arg) {
  return TypeJudgment({
    arg,
  });
}

export function isNumber(arg) {
  return TypeJudgment({
    arg,
    type: 2,
  });
}

export function isString(arg) {
  return TypeJudgment({
    arg,
    type: 3,
  });
}

const timeType = {
  s: 1,
  m: 2,
  h: 3,
};

/**
 * 时分秒转化
 * @date   2019-07-10
 * @param  {[time]}   number
 * @param  {[from]}   
 * @param  {[to]}
 * @return {number}
 */
export function formatTime({
  time,
  from = 'm',
  to = 's',
}) {
  if (!timeType[from] || !timeType[to]) {
    throw new Error('传入的参数有误');
  }
  const diff = timeType[from] - timeType[to];
  return time * Math.pow(60, diff);
}

/**
 * 时间戳格式化
 * @date   2019-07-04
 * @param  {[type]}   unix 时间戳
 * @param  {[type]}   fmt  时间格式  Y-M-D h:m:s
 * @return {string}
 */
export function formatUnix({
  unix,
  fmt,
}) {
  if (!isString(fmt)) {
    throw new Error('传入的参数有误');
  }

  const date = new Date(unix * 1000);
  const map = {
    Y: date.getFullYear(),
    M: date.getMonth() + 1,
    D: date.getDate(),
    h: date.getHours(),
    m: date.getMinutes(),
    s: date.getSeconds(),
  };

  Object.keys(map).forEach((k) => {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(RegExp.$1, addZero(map[k]));
    }
  });
  return fmt;
}

function addZero(num) {
  return num < 10 ? `0${num}` : num;
}

/**
 * 检查url格式
 * @date   2019-07-19
 * @param  {string}   url 
 * @return {boolean}     
 */
export function checkUrl(url) {
  return url.match(/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g);
}